package com.minelx.statementplus.ui.form.ui.memberbased.addingfield;

import com.minelx.sqlstructures.core.table.ITable;
import com.minelx.sqlstructures.core.values.FieldValues;
import com.minelx.statementplus.ui.form.swing.DatabaseToNode;
import com.minelx.woods.task.core.values.FieldPathValues;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.util.Arrays;

public class DatabasePath {
	private final DefaultMutableTreeNode[] path;

	private DatabasePath(DefaultMutableTreeNode[] path) {
		this.path = path;
	}

	public FieldPathValues createValue() {
		String tableName = ((ITable) ((DatabaseToNode.NodeAdapter) path[1].getUserObject()).get()).getName();
		FieldValues fieldDTO = ((FieldValues) ((DatabaseToNode.NodeAdapter) path[2].getUserObject()).get());
		return new FieldPathValues(tableName, fieldDTO.getName(), fieldDTO.getComment());
	}

	public static DatabasePath create(TreePath treePath) {
		DefaultMutableTreeNode[] path = Arrays.stream(treePath.getPath())
				.map(item -> ((DefaultMutableTreeNode) item))
				.toArray(DefaultMutableTreeNode[]::new);
		return new DatabasePath(path);
	}
}
